/*

HS	Hiscore table handler

(C) 12/8/88  A.Key

*/

#include <stdio.h>
#include "standard.h"

/*
Stuff associated with hi-scores
*/

#define	L_NAME	20

typedef struct hs_struct
	{
	long	hs_score;
	char	hs_name [L_NAME+1];
	} HS;

#define	N_HS	10

static HS hs_default = { 100L, "ANDY" };

static HS hs_table [N_HS];

void	hs_init(char *fn)
	{
	FILE	*fp;
	int	i;

	if ( (fp = fopen(fn, "rb")) != NULL )
		/* initialise from previous contents of hiscore file */
		{
		fread(hs_table, sizeof(hs_table), 1, fp);
		fclose(fp);
		}
	else
		/* set each entry to a default */
		for ( i = 0; i < N_HS; i++ )
			memcpy(&hs_table [i], &hs_default, sizeof(HS));
	}

void	hs_deinit(char *fn)
	{
	FILE	*fp;

	if ( (fp = fopen(fn, "wb")) != NULL )
		/* write out to a file */
		{
		fwrite(hs_table, sizeof(hs_table), 1, fp);
		fclose(fp);
		}
	}

/*
Notice that in the following the > test ensures that the first person
to get a particular score is the one who is highest in the table.
*/

int	hs_where_to_insert(long score)	/* returns position in table to      */
					/* insert, or -1 if not good enough  */
	{
	int	i;

	for ( i = 0; i < N_HS; i++ )
		if ( score > hs_table [i].hs_score )
			return ( i );
	return ( -1 );
	}

void	hs_insert(long score, char *name, int posn)
	{
	int	i;

	for ( i = N_HS - 2; i >= posn; i-- )
		memcpy(&hs_table [i + 1], &hs_table [i], sizeof(HS));
	hs_table [posn].hs_score = score;
	strcpy(hs_table [posn].hs_name, name);		
	}

long	hs_get_score(int i)
	{
	return ( hs_table [i].hs_score );
	}

char	*hs_get_name(int i)
	{
	return ( hs_table [i].hs_name );
	}
